<template>
    <el-card>
        <div class="search-query">
            <el-form :inline="true" :model="searchForm" ref="searchFormRef">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="searchForm.username" placeholder="用户名" clearable />
                </el-form-item>
                <el-form-item label="电话号码" prop="phone">
                    <el-input v-model="searchForm.phone" placeholder="电话号码" clearable />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="handleSearchReset(searchFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="table-btn">
            <el-space :size="10">
                <el-button type="primary" @click="handleAddView" v-if="store.checkPermission('user:add')">新增</el-button>
                <el-dropdown placement="bottom-start" v-if="store.checkPermission('user:export')">
                    <el-button type="primary">导出 </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="handleSelectExport">选择导出</el-dropdown-item>
                            <el-dropdown-item @click="handleAllExport">全部导出</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
                <el-button type="primary" @click="handleResetPassword">重置密码</el-button>
            </el-space>

            <el-button type="primary" @click="handleReflesh">刷新</el-button>
        </div>

        <el-table border :data="userData.list" v-loading="loading" style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="avatar" label="头像">
                <template v-slot="scope"  #default>
                    <el-avatar size="default" :src="scope.row.avatar"  />
                </template>
            </el-table-column>
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="sex" label="性别">
                <template v-slot="scope"  #default>
                    <el-tag v-if="scope.row.sex == 1" type="primary">男</el-tag>
                    <el-tag v-if="scope.row.sex == 0" type="success">女</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="phone" label="电话号码" />
            <el-table-column prop="email" label="电子邮箱" />
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column prop="updateTime" label="更新时间" />
            <el-table-column fixed="right" label="操作">
                <template v-slot="scope" #default>
                    <el-space wrap>
                        <el-button type="primary" @click="handleAssginView(scope.row)" link>分配角色</el-button>
                        <el-button type="success" @click="handleEdit(scope.row)" link>编辑</el-button>
                        <el-button type="danger" @click="handleDelete(scope.row)" link>删除</el-button>

                    </el-space>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="userData.currentPage" v-model:page-size="userData.pageSize"
            :page-sizes="[10, 20, 50, 100]" background="background" layout="total, sizes, prev, pager, next,jumper"
            :total="userData.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑 -->
    <el-dialog v-model="visible" :title="addForm.id ? '编辑' : '新增'" width="500" :close-on-click-modal="false">
        <el-form :model="addForm" label-position="top" :rules="rules" ref="addFormRef">

            <el-form-item label="头像">
                <el-upload action="/api/file/upload" list-type="picture-card" :on-success="handleAvatarSuccess"
                    :show-file-list="false" v-if="!imageUrl">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <div class="image-container" v-if="imageUrl">
                    <el-image  style="width: 100px; height: 100px" :src="imageUrl"
                        fit="fill" :preview-src-list="[imageUrl]" class="image-item" />

                    <el-button class="delete-btn" type="danger" icon="Delete" circle
                        @click="handleAvatarDelete"></el-button>
                </div>

            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="addForm.sex">
                    <el-radio :value="1">男</el-radio>
                    <el-radio :value="0">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username" placeholder="请输入用户名" clearable />
            </el-form-item>

            <el-form-item label="密码" prop="password">
                <el-input :disabled="addForm.id ? true : false" v-model="addForm.password" type="password"
                    placeholder="请输入密码" show-password clearable />
            </el-form-item>
            <el-form-item label="电话号码" prop="phone">
                <el-input v-model="addForm.phone" placeholder="请输入电话号码" maxlength="11" clearable />
            </el-form-item>
            <el-form-item label="电子邮箱" prop="email">
                <el-input v-model="addForm.email" placeholder="请输入电子邮箱" clearable />
            </el-form-item>

        </el-form>
        <template #footer>
            <div>
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd(addFormRef)">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-drawer v-model="drawerVisible" direction="rtl" :close-on-click-modal="false">
        <template #header>
            <h4>分配角色</h4>
        </template>
        <template #default>
            <el-select multiple v-model="sysUserRoleDto.roleIds" placeholder="请分配角色" @change="handleSelectRole">
                <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>

        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button type="primary" @click="handleAssginRole">保存</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="js">

import { ref, onMounted } from 'vue'
import user from '@/services/user'
import role from '@/services/role'
import { userStore } from '@/stores/userStore'
import { ElMessage, ElMessageBox } from 'element-plus'


const store = userStore()
const userData = ref({
    'currentPage': 1,
    'pageSize': 10,
    'list': [],
    'total': 0
})

const imageUrl = ref('')
const loading = ref(false)
const visible = ref(false)
const addFormRef = ref()
const addForm = ref({
    id: '',
    username: '',
    password: '',
    phone: '',
    email: '',
    avatar: '',
    sex: ''
})

const rules = ref({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },

    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] },
    ],
})

onMounted(() => {
    init()
})

// 初始化
const init = async () => {
    loading.value = true
    const res = await user.pageUser({})
    if (res.code === 200) {
        userData.value = res.data
        loading.value = false
    }
}

// 当前页大小
const handleSizeChange = async (pageSize) => {
    loading.value = true
    const data = {
        ...searchForm,
        pageSize
    }
    const res = await user.pageUser(data)
    if (res.code === 200) {
        userData.value = res.data
        loading.value = false
    }
}

// 当前页数
const handleCurrentChange = async (currentPage) => {
    loading.value = true
    const data = {
        ...searchForm,
        currentPage
    }
    const res = await user.pageUser(data)
    if (res.code === 200) {
        userData.value = res.data
        loading.value = false
    }
}

// 编辑
const handleEdit = (row) => {
    addForm.value = JSON.parse(JSON.stringify(row)) // 改过之后的
    imageUrl.value = row.avatar
    visible.value = true
}

// 删除
const handleDelete = async (row) => {
    const res = await user.deleteUserByIds([row.id])
    if (res.code === 200) {
        init()
        ElMessage({
            type: 'success',
            message: res.msg
        })
    }
}

// 新增弹窗
const handleAddView = () => {
    visible.value = true
    addForm.value = {}
}

// 新增
const handleAdd = async (formRef) => {
    if (!formRef) return
    await formRef.validate((valid, fields) => {
        if (valid) {
            user.saveUser(addForm.value).then((res) => {
                if (res.code == 200) {
                    ElMessage({
                        message: res.msg,
                        type: 'success'
                    })
                    init()
                }
            })

            visible.value = false
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 刷新
const handleReflesh = () => {
    init()
}

const searchFormRef = ref()
const searchForm = ref({
    username: '',
    phone: ''
})
// 搜素
const handleSearch = async () => {
    loading.value = true
    const res = await user.pageUser(searchForm.value)
    if (res.code === 200) {
        userData.value = res.data
        loading.value = false
    }
}
// 搜索重置
const handleSearchReset = (formRef) => {
    formRef.resetFields()
}

// 复选框
let ids = []
const handleSelectionChange = (value) => {
    ids = []
    value.forEach(e => {
        ids.push(e.id)
    });
}

// 批量删除
const handleBatchDelete = async () => {
    if (ids.length == 0) {
        throw ElMessage({
            type: 'warning',
            message: "请选择"
        })
    }
    const res = await user.deleteUserByIds(ids)
    if (res.code === 200) {
        init()
        ElMessage({
            type: 'success',
            message: res.msg
        })
    }
}

// 选择导出
const handleSelectExport = async () => {
    if (ids.length > 0) {
        await user.exportUser({ ids: ids })
    } else {
        ElMessage({
            type: 'warning',
            message: '请选择'
        })
    }
}
// 全部导出
const handleAllExport = async () => {
    await user.exportUser(searchForm.value)
}
// 重置密码
const handleResetPassword = async () => {
    if (ids.length == 1) {
        const res = await user.resetPassword({ id: ids[0] })
        if (res.code === 200) {
            ElMessageBox.alert(res.data, '', {
                confirmButtonText: '确定',
                center: true
            })
        }
    } else {
        ElMessage({
            type: 'warning',
            message: '请勾选|只能勾选一个'
        })
    }

}
// 分配角色
const roleList = ref()
const sysUserRoleDto = ref({
    'userId': '',
    'roleIds': []
})
const drawerVisible = ref(false)
const handleAssginView = async (row) => {
    sysUserRoleDto.value.userId = row.id
    const res = await role.listRoles()
    if (res.code === 200) {
        roleList.value = res.data
    }

    const uRes = await user.listRolesByUserId({ userId: row.id })
    if (uRes.code === 200) {
        sysUserRoleDto.value.roleIds = uRes.data
    }

    drawerVisible.value = true
}

// 选择角色
const handleSelectRole = (value) => {
    sysUserRoleDto.value.roleIds = value
}

// 分配角色
const handleAssginRole = async () => {
    const res = await user.assignRole(sysUserRoleDto.value)
    if (res.code === 200) {
        ElMessage({
            type: 'success',
            message: res.msg
        })
        drawerVisible.value = false
    }

}

// 上传头像
const handleAvatarSuccess = (res, uploadFile) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw)
    addForm.value.avatar = res.data
}

// 删除头像
const handleAvatarDelete = () => {
    imageUrl.value = ''
};
</script>

<style lang="less" scoped>
.el-pagination {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
}

.table-btn {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
}

.operate {
    display: flex;
    justify-content: space-around;
}

.image-container {
  position: relative;
  display: inline-block;
  margin: 10px;
}

.image-item {
  width: 200px;
  height: 200px;
  border-radius: 4px;
}

.delete-btn {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 24px;
  height: 24px;
  font-size: 12px;
  padding: 0;
  z-index: 1;
}

</style>
